package cn.com.surker.weight.service.impl;

import cn.com.surker.common.Code;
import cn.com.surker.database.JDBCTemplateCache;
import cn.com.surker.enums.StateEnum;
import cn.com.surker.enums.oa.CarTypeEnum;
import cn.com.surker.enums.system.DataBaseEnum;
import cn.com.surker.enums.weight.OrderWeightTypeEnum;
import cn.com.surker.enums.weight.WeightCarTypeEnum;
import cn.com.surker.platform.entity.PlatformUser;
import cn.com.surker.production.entity.ProTicketOrder;
import cn.com.surker.system.dao.DataSourceInfoDao;
import cn.com.surker.system.entity.DataSourceInfo;
import cn.com.surker.util.DateUtil;
import cn.com.surker.util.MathUtils;
import cn.com.surker.util.StringUtils;
import cn.com.surker.wechat.WechatAccountApi;
import cn.com.surker.weight.entity.WeightOrder;
import cn.com.surker.weight.dao.WeightOrderDao;
import cn.com.surker.weight.service.WeightOrderService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import cn.com.surker.spring.RestResultDto;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * <p>
 * 过磅订单表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2024-11-06
 */
public abstract class WeightOrderServiceImpl extends ServiceImpl<WeightOrderDao, WeightOrder> implements WeightOrderService {

	@Resource
	protected WeightOrderDao weightOrderDao;
	@Resource
	protected DataSourceInfoDao dsDao;

	@Override
	public WeightOrder getById(Serializable id) {
		if (id == null) {
			return null;
		}
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("id", id);
		qw.last("limit 1");
		WeightOrder weightOrder = weightOrderDao.selectOne(qw);
		return weightOrder;
	}

	@Override
	public WeightOrder queryByCode(String code) {
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("code", code);
		qw.last("limit 1");
		WeightOrder weightOrder = weightOrderDao.selectOne(qw);
		return weightOrder;
	}

	@Override
	public Integer deleteById(Long id) {
		if (id == null) {
			return -1;
		}
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("id", id);
		uw.set("status", StateEnum.DISABLED.getCode());
		uw.set("update_time", new Date());
		int update = weightOrderDao.update(null, uw);
		return update;
	}

	@Override
	public Integer deleteByCode(String code) {
		if (StringUtils.isBlank(code)) {
			return -1;
		}
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("code", code);
		uw.set("status", StateEnum.DISABLED.getCode());
		uw.set("update_time", new Date());
		int update = weightOrderDao.update(null, uw);
		return update;
	}

	@Override
	public List<WeightOrder> waitList() {
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("check_status", 0);
		List<WeightOrder> orderList = weightOrderDao.selectList(qw);
		return orderList;
	}

	@Override
	public Integer adopt(String uCode, String checker, String position, String positionName, Double minusWeight, String wxCode, String driverName) {
		if (StringUtils.isBlank(uCode) || StringUtils.isBlank(position)) {
			return -1;
		}
		if (minusWeight == null) {
			minusWeight = 0d;
		} else {
			minusWeight = MathUtils.multiply(minusWeight, 1000d);
		}
		//	审核通过
		Integer checkStatus = 1;
		// 修改过磅程序的数据,只更新本地表
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.set("check_status", checkStatus);
		uw.set("checker", checker);
		uw.set("minus_weight", minusWeight);
		uw.set("storage_id", position);
		uw.set("storage", positionName);
		uw.eq("code", uCode);
		int update = weightOrderDao.update(null, uw);
		if (update > 0) {
			//	更新成功
			sendMessage();
		} else {
			return update;
		}
		return update;
	}

	@Override
	public Integer refuse(String code, String userName, String remarks, String wxCode, String driverName) {
		if (StringUtils.isBlank(code)) {
			return -1;
		}
		if (StringUtils.isBlank(remarks)) {
			remarks = "";
		}
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("code", code);
		uw.set("check_status", 2);
		uw.set("checker", userName);
		uw.set("remark", remarks);
		int update = weightOrderDao.update(null, uw);
		if (update > 0) {
			sendMessage();
			/*try {
			PlatformUser user = platformUserDao.findByOpenid(wxCode);
			if (user != null && !StringUtils.isNull(user.getAccountOpenid())) {
				Date nowDate = new Date();
				String remark = "如有疑问可联系材料调度员、材料统计员、材料经理,审核拒绝时间:" + DateUtil.convertString(nowDate, "yyyy年MM月dd日 HH时mm分");
				Integer result = WechatAccountApi.sendServiceMessage(user.getAccountOpenid(), "无人过磅工单审核拒绝通知", "#1890ff",
					"尊敬的" + driverName + "师傅,您提交的工单已经被拒绝,拒绝原因:" + remarks, "#1890ff",
					remark, "#F1826E", "https://weight.chixugroup.com/cloud/weight/order-detail?openid=" + wxCode);
				if (result == 1)
					platformUserDao.updateClearOpenid(wxCode);
			}
		} catch (Exception e) {
			log.error("无人过磅审核拒绝推送消息失败:" + e.getMessage());
		}*/
		}
		return update;
	}

	@Override
	public List<WeightOrder> againList() {
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("two_check", 1);
		List<WeightOrder> orderList = weightOrderDao.selectList(qw);
		return orderList;
	}

	@Override
	public Integer adoptAgain(String uCode) {
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("code", uCode);
		uw.set("two_check", 2);
		int update = weightOrderDao.update(null, uw);
		return update;
	}

	@Override
	public Integer spotCheck(String code, String wxCode, String driverName) {
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("code", code);
		uw.set("check_status", 3);
		int update = weightOrderDao.update(null, uw);
		//	发送消息
		sendMessage();
		/*PlatformUser user = platformUserDao.findByOpenid(wxCode);
		if (user != null && !StringUtils.isNull(user.getAccountOpenid())) {
			Date nowDate = new Date();
			String remark = "如有疑问可联系材料调度员、材料统计员、材料经理,审核通过时间:" + DateUtil.convertString(nowDate, "yyyy年MM月dd日 HH时mm分");
			Integer result = WechatAccountApi.sendServiceMessage(user.getAccountOpenid(), "无人过磅工单审核通过通知", "#1890ff",
				"尊敬的" + driverName + "师傅,您的工单已经审核通过,但需要抽检,请上磅,称量毛重后,请下磅等待检测员取样", "#1890ff",
				remark, "#F1826E", "https://weight.chixugroup.com/cloud/weight/order-detail?openid=" + wxCode);
			if (result == 1)
				platformUserDao.updateClearOpenid(wxCode);
		}*/
		return update;
	}

	@Override
	public List<WeightOrder> checkList() {
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("check_status", 3);
		List<WeightOrder> orderList = weightOrderDao.selectList(qw);
		return orderList;
	}

	@Override
	public Page<WeightOrder> unskinnedList(Integer offset, Integer limit) {
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		qw.eq("order_status", 0);
		qw.eq("storage_type", 0);
		qw.gt("gross", 0);
		qw.orderByAsc("id");
		PageHelper.offsetPage(offset, limit);
		Page<WeightOrder> weightOrderPage = weightOrderDao.selectPage(new Page<>((offset + limit) / limit, limit), qw);
		/**分页插件**/
		if (!StringUtils.isNull(weightOrderPage.getRecords())) {
			PageInfo pageInfo = new PageInfo(weightOrderPage.getRecords());
			if (!StringUtils.isNull(pageInfo.getTotal()))
				weightOrderPage.setTotal(pageInfo.getTotal());
		}
		return weightOrderPage;
	}

	@Override
	public Boolean compDo(String code) {
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("code", code);
		uw.set("order_status", 6);
		int update = weightOrderDao.update(null, uw);
		if (update > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Integer updatePosition(String code, String position, String positionName) {
		if (StringUtils.isBlank(position)) {
			return Code.FAILED.getCode();
		}
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("code", code);
		uw.set("storage_id", position);
		uw.set("storage", positionName);
		weightOrderDao.update(null, uw);
		//	todo 更新erp本地数据
		/*String localErpSql = "update Material_WeighingData_T set Sys_Storage_ID = ?,remark = ? where code = ?";
		int updateErp = localJdbcTemplate.update(localErpSql, obj);*/
		return Code.SUCCESS.getCode();
	}

	@Override
	public Integer updateCreTime(String code, String creTime) {
		UpdateWrapper<WeightOrder> uw = new UpdateWrapper<>();
		uw.eq("code", code);
		uw.set("create_time", creTime);
		int update = weightOrderDao.update(null, uw);
		return update;
	}

	@Override
	public IPage<WeightOrder> grossPage(String searchVal, Integer examineStatus, Date sTime, Date eTime, Integer offset, Integer limit) {
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		if (StringUtils.isNotBlank(searchVal)) {
			qw.like("bus_number", searchVal);
		}
		if (examineStatus != null) {
			qw.eq("check_status", examineStatus);
		}
		if (sTime != null) {
			qw.ge("create_time", sTime);
		}
		if (eTime != null) {
			qw.lt("create_time", eTime);
		}
		qw.isNotNull("gross");
		qw.orderByAsc("id");
		PageHelper.offsetPage(offset, limit);
		Page<WeightOrder> weightOrderPage = weightOrderDao.selectPage(new Page<>((offset + limit) / limit, limit), qw);
		/**分页插件**/
		if (!StringUtils.isNull(weightOrderPage.getRecords())) {
			PageInfo pageInfo = new PageInfo(weightOrderPage.getRecords());
			if (!StringUtils.isNull(pageInfo.getTotal()))
				weightOrderPage.setTotal(pageInfo.getTotal());
		}
		return weightOrderPage;
	}

	@Override
	public IPage<WeightOrder> findPage(String searchVal, Integer examineStatus, Date startTime, Date endTime, Integer offset, Integer limit) {
		QueryWrapper<WeightOrder> qw = new QueryWrapper<>();
		qw.eq("status", StateEnum.ENABLED.getCode());
		if (StringUtils.isNotBlank(searchVal)) {
			qw.like("bus_number", searchVal);
		}
		if (examineStatus != null) {
			qw.eq("check_status", examineStatus);
		}
		if (startTime != null) {
			qw.ge("create_time", startTime);
		}
		if (endTime != null) {
			qw.lt("create_time", endTime);
		}
		qw.orderByAsc("id");
		PageHelper.offsetPage(offset, limit);
		Page<WeightOrder> weightOrderPage = weightOrderDao.selectPage(new Page<>((offset + limit) / limit, limit), qw);
		/**分页插件**/
		if (!StringUtils.isNull(weightOrderPage.getRecords())) {
			PageInfo pageInfo = new PageInfo(weightOrderPage.getRecords());
			if (!StringUtils.isNull(pageInfo.getTotal()))
				weightOrderPage.setTotal(pageInfo.getTotal());
		}
		return weightOrderPage;
	}

	/**
	 * 查询过磅原始订单
	 * @param searchVal
	 * @param startTime
	 * @param endTime
	 * @param offset
	 * @param limit
	 * @return
	 */
	public IPage<WeightOrder> findInitPage(Long orgId, String searchVal, Integer weightType, Integer carType,
										   Integer searchType, String startTime, String endTime, Integer offset, Integer limit) {
		if (StringUtils.isNull(orgId))
			return null;
		if (StringUtils.isNull(searchType))
			searchType = 0;//已完成过磅数据

		DataSourceInfo ds = dsDao.queryDSByOriginIdV1(orgId, DataBaseEnum.MYSQL.getCode());
		if (ds == null)
			return null;
		QueryWrapper<WeightOrder> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("org_id", orgId);
		if (!StringUtils.isNull(weightType))
			queryWrapper.eq("weight_type", weightType);
		else
			queryWrapper.eq("weight_type", OrderWeightTypeEnum.YC.getCode());
		if (!StringUtils.isNull(carType))
			queryWrapper.eq("car_type", carType);
		else
			queryWrapper.eq("car_type", WeightCarTypeEnum.MATERIAL.getCode());

		if (searchType == 0) {
			if (startTime != null) {
				queryWrapper.ge("out_time", startTime);
			}
			if (endTime != null) {
				queryWrapper.lt("out_time", endTime);
			}
			queryWrapper.ge("gross", 0);
			queryWrapper.orderByDesc("out_time");
		} else {//全部订单
			if (startTime != null) {
				queryWrapper.ge("create_time", startTime);
			}
			if (endTime != null) {
				queryWrapper.lt("create_time", endTime);
			}
			queryWrapper.orderByDesc("create_time");
		}

		PageHelper.offsetPage(offset, limit);
		Page<WeightOrder> weightOrderPage = weightOrderDao.findDbPage(new Page<>((offset + limit) / limit, limit), queryWrapper, ds.getCode());
		/**分页插件**/
		if (!StringUtils.isNull(weightOrderPage.getRecords())) {
			PageInfo pageInfo = new PageInfo(weightOrderPage.getRecords());
			if (!StringUtils.isNull(pageInfo.getTotal()))
				weightOrderPage.setTotal(pageInfo.getTotal());
		}
		return weightOrderPage;
	}

	protected void sendMessage() {
		/*try {
			PlatformUser user = platformUserDao.findByOpenid(wxCode);
			if (user != null && !StringUtils.isNull(user.getAccountOpenid())) {
				Date nowDate = new Date();
				String remark = "如有疑问可联系材料调度员、材料统计员、材料经理,审核完成时间:" + DateUtil.convertString(nowDate, "yyyy年MM月dd日 HH时mm分");
				Integer result = WechatAccountApi.sendServiceMessage(user.getAccountOpenid(), "无人过磅工单审核完成通知", "#1890ff",
					"您的工单已通过,仓位:" + positionName, "#1890ff",
					remark, "#F1826E", "https://weight.chixugroup.com/cloud/weight/order-detail?openid=" + wxCode);
				if (result == 1){
					platformUserDao.updateClearOpenid(wxCode);
				}
			}
		} catch (Exception e) {
			log.error("无人过磅审核成功推送消息失败:" + e.getMessage());
		}*/

	}

	;


	protected BeanPropertyRowMapper<WeightOrder> orderRowMapper() {
		BeanPropertyRowMapper<WeightOrder> rowMapper = BeanPropertyRowMapper.newInstance(WeightOrder.class);
		return rowMapper;
	}
}